package thread;

/**
 * Created by User on 2018/1/10.
 */
public class ThreadJoin {

    static final int TOTAL_THREADS = 100;

    public static void main(String[] args) throws InterruptedException {
        VolatileData volatileData = new VolatileData();

        Thread[] threads = new Thread[TOTAL_THREADS];
        for (int i = 0; i < TOTAL_THREADS; ++i)
            threads[i] = new VolatileThread(volatileData);

        //开始读取变量值的操作
        for (int i = 0; i < TOTAL_THREADS; ++i)
            threads[i].start();

        //等待所有线程操作终止
        for (int i = 0; i < TOTAL_THREADS; ++i)
            threads[i].join();

        System.out.println(volatileData.counter);
    }


    static class VolatileThread extends Thread {
        private final VolatileData volatileData;

        public VolatileThread(VolatileData volatileData) {
            this.volatileData = volatileData;
        }

        /**
         * 调用VolatileData类中的两个方法，进行取值和自增操作
         */
        @Override
        public void run() {
            for (int i = 0; i < 1000; i++) {
                int oldValue = volatileData.getCounter();
//                System.out.println("[Thread " + Thread.currentThread().getId() + "]: Old value = " + oldValue);
                volatileData.increaseCounter();
                int newValue = volatileData.getCounter();
//                System.out.println("[Thread " + Thread.currentThread().getId() + "]: New value = " + newValue);
            }
        }
    }

    static class VolatileData {

        //声明为volatile类型
        private volatile int counter = 0;

        /**
         * 返回counter变量的值
         *
         * @return
         */
        public int getCounter() {
            return counter;
        }

        /**
         * 自增counter变量的值
         */
        public void increaseCounter() {
            ++counter;
        }
    }

}
